home *** CD-ROM | disk | FTP | other *** search
/ Revista do CD-ROM 151 / cd-rom 151.iso / internet / firefox / Firefox Setup 3.0 Beta 1.exe / nonlocalized / components / nsMicrosummaryService.js < prev    next >
Encoding:
Text File  |  2007-11-09  |  75.0 KB  |  2,247 lines

  1. //@line 40 "e:\builds\tinderbox\Fx-Rel\WINNT_5.2_Depend\mozilla\browser\components\microsummaries\src\nsMicrosummaryService.js"
  2.  
  3. const Cc = Components.classes;
  4. const Ci = Components.interfaces;
  5. const Cr = Components.results;
  6. const Cu = Components.utils;
  7.  
  8. const PERMS_FILE    = 0644;
  9. const MODE_WRONLY   = 0x02;
  10. const MODE_CREATE   = 0x08;
  11. const MODE_TRUNCATE = 0x20;
  12.  
  13. const NS_ERROR_MODULE_DOM = 2152923136;
  14. const NS_ERROR_DOM_BAD_URI = NS_ERROR_MODULE_DOM + 1012;
  15.  
  16. // How often to check for microsummaries that need updating, in milliseconds.
  17. const CHECK_INTERVAL = 15 * 1000; // 15 seconds
  18. // How often to check for generator updates, in seconds
  19. const GENERATOR_INTERVAL = 7 * 86400; // 1 week
  20.  
  21. const MICSUM_NS = "http://www.mozilla.org/microsummaries/0.1";
  22. const XSLT_NS = "http://www.w3.org/1999/XSL/Transform";
  23.  
  24. const ANNO_MICSUM_GEN_URI    = "microsummary/generatorURI";
  25. const ANNO_MICSUM_EXPIRATION = "microsummary/expiration";
  26. const ANNO_STATIC_TITLE      = "bookmarks/staticTitle";
  27. const ANNO_CONTENT_TYPE      = "bookmarks/contentType";
  28.  
  29. const MAX_SUMMARY_LENGTH = 4096;
  30.  
  31. Cu.import("resource://gre/modules/XPCOMUtils.jsm");
  32.  
  33. function MicrosummaryService() { this._init() }
  34.  
  35. MicrosummaryService.prototype = {
  36.   // Bookmarks Service
  37.   __bms: null,
  38.   get _bms() {
  39.     if (!this.__bms)
  40.       this.__bms = Cc["@mozilla.org/browser/nav-bookmarks-service;1"].
  41.                    getService(Ci.nsINavBookmarksService);
  42.     return this.__bms;
  43.   },
  44.  
  45.   // Annotation Service
  46.   __ans: null,
  47.   get _ans() {
  48.     if (!this.__ans)
  49.       this.__ans = Cc["@mozilla.org/browser/annotation-service;1"].
  50.                    getService(Ci.nsIAnnotationService);
  51.     return this.__ans;
  52.   },
  53.  
  54.   // IO Service
  55.   __ios: null,
  56.   get _ios() {
  57.     if (!this.__ios)
  58.       this.__ios = Cc["@mozilla.org/network/io-service;1"].
  59.                    getService(Ci.nsIIOService);
  60.     return this.__ios;
  61.   },
  62.  
  63.   // Observer Service
  64.   __obs: null,
  65.   get _obs() {
  66.     if (!this.__obs)
  67.       this.__obs = Cc["@mozilla.org/observer-service;1"].
  68.                    getService(Ci.nsIObserverService);
  69.     return this.__obs;
  70.   },
  71.  
  72.   /**
  73.    * Make a URI from a spec.
  74.    * @param   spec
  75.    *          The string spec of the URI.
  76.    * @returns An nsIURI object.
  77.    */
  78.   _uri: function MSS__uri(spec) {
  79.     return this._ios.newURI(spec, null, null);
  80.   },
  81.  
  82.   // Directory Locator
  83.   __dirs: null,
  84.   get _dirs() {
  85.     if (!this.__dirs)
  86.       this.__dirs = Cc["@mozilla.org/file/directory_service;1"].
  87.                    getService(Ci.nsIProperties);
  88.     return this.__dirs;
  89.   },
  90.  
  91.   // The update interval as specified by the user (defaults to 30 minutes)
  92.   get _updateInterval() {
  93.     var updateInterval =
  94.       getPref("browser.microsummary.updateInterval", 30);
  95.     // the minimum update interval is 1 minute
  96.     return Math.max(updateInterval, 1) * 60 * 1000;
  97.   },
  98.  
  99.   __branch: null,
  100.   get _branch() {
  101.     if (!this.__branch) {
  102.       var prefs = Cc["@mozilla.org/preferences-service;1"].
  103.                   getService(Ci.nsIPrefService);
  104.       this.__branch = prefs.getBranch("browser.microsummary.");
  105.       this.__branch.QueryInterface(Ci.nsIPrefBranch2);
  106.     }
  107.     return this.__branch;
  108.   },
  109.  
  110.   // A cache of local microsummary generators.  This gets built on startup
  111.   // by the _cacheLocalGenerators() method.
  112.   _localGenerators: {},
  113.  
  114.   // The timer that periodically checks for microsummaries needing updating.
  115.   _timer: null,
  116.  
  117.   // XPCOM registration
  118.   classDescription: "Microsummary Service",
  119.   contractID: "@mozilla.org/microsummary/service;1",
  120.   classID: Components.ID("{460a9792-b154-4f26-a922-0f653e2c8f91}"),
  121.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIMicrosummaryService, 
  122.                                          Ci.nsISupportsWeakReference,
  123.                                          Ci.nsIObserver]),
  124.  
  125.   // nsIObserver
  126.   observe: function MSS_observe(subject, topic, data) {
  127.     switch (topic) {
  128.       case "xpcom-shutdown":
  129.         this._destroy();
  130.         break;
  131.       case "nsPref:changed":
  132.         if (data == "enabled")
  133.           this._initTimers();
  134.         break;
  135.     }
  136.   },
  137.  
  138.   _init: function MSS__init() {
  139.     this._obs.addObserver(this, "xpcom-shutdown", true);
  140.     this._branch.addObserver("", this, true);
  141.     this._initTimers();
  142.     this._cacheLocalGenerators();
  143.   },
  144.  
  145.   _initTimers: function MSS__initTimers() {
  146.     if (this._timer)
  147.       this._timer.cancel();
  148.  
  149.     if (!getPref("browser.microsummary.enabled", true))
  150.       return;
  151.  
  152.     // Periodically update microsummaries that need updating.
  153.     this._timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  154.     var callback = {
  155.       _svc: this,
  156.       notify: function(timer) { this._svc._updateMicrosummaries() }
  157.     };
  158.     this._timer.initWithCallback(callback,
  159.                                  CHECK_INTERVAL,
  160.                                  this._timer.TYPE_REPEATING_SLACK);
  161.  
  162.     // Setup a cross-session timer to periodically check for generator updates.
  163.     var updateManager = Cc["@mozilla.org/updates/timer-manager;1"].
  164.                         getService(Ci.nsIUpdateTimerManager);
  165.     var interval = getPref("browser.microsummary.generatorUpdateInterval",
  166.                            GENERATOR_INTERVAL);
  167.     var updateCallback = {
  168.       _svc: this,
  169.       notify: function(timer) { this._svc._updateGenerators() }
  170.     };
  171.     updateManager.registerTimer("microsummary-generator-update-timer",
  172.                                 updateCallback, interval);
  173.   },
  174.   
  175.   _destroy: function MSS__destroy() {
  176.     this._timer.cancel();
  177.     this._timer = null;
  178.   },
  179.  
  180.   _updateMicrosummaries: function MSS__updateMicrosummaries() {
  181.     var bookmarks = this._getBookmarks();
  182.  
  183.     var now = Date.now();
  184.     var updateInterval = this._updateInterval;
  185.     for ( var i = 0; i < bookmarks.length; i++ ) {
  186.       var bookmarkID = bookmarks[i];
  187.  
  188.       // Skip this page if its microsummary hasn't expired yet.
  189.       if (this._ans.itemHasAnnotation(bookmarkID, ANNO_MICSUM_EXPIRATION) &&
  190.           this._ans.getItemAnnotation(bookmarkID, ANNO_MICSUM_EXPIRATION) > now)
  191.         continue;
  192.  
  193.       // Reset the expiration time immediately, so if the refresh is failing
  194.       // we don't try it every 15 seconds, potentially overloading the server.
  195.       this._setAnnotation(bookmarkID, ANNO_MICSUM_EXPIRATION, now + updateInterval);
  196.  
  197.       // Try to update the microsummary, but trap errors, so an update
  198.       // that throws doesn't prevent us from updating the rest of them.
  199.       try {
  200.         this.refreshMicrosummary(bookmarkID);
  201.       }
  202.       catch(ex) {
  203.         Cu.reportError(ex);
  204.       }
  205.     }
  206.   },
  207.  
  208.   _updateGenerators: function MSS__updateGenerators() {
  209.     var generators = this._localGenerators;
  210.     var update = getPref("browser.microsummary.updateGenerators", true);
  211.     if (!generators || !update)
  212.       return;
  213.  
  214.     for (let uri in generators)
  215.       generators[uri].update();
  216.   },
  217.  
  218.   _updateMicrosummary: function MSS__updateMicrosummary(bookmarkID, microsummary) {
  219.     var title = this._bms.getItemTitle(bookmarkID);
  220.  
  221.     // Ensure the user-given title is cached
  222.     if (!this._ans.itemHasAnnotation(bookmarkID, ANNO_STATIC_TITLE))
  223.       this._setAnnotation(bookmarkID, ANNO_STATIC_TITLE, title);
  224.  
  225.     // A string identifying the bookmark to use when logging the update.
  226.     var bookmarkIdentity = bookmarkID;
  227.  
  228.     // Update if the microsummary differs from the current title.
  229.     if (!title || title != microsummary.content) {
  230.       this._bms.setItemTitle(bookmarkID, microsummary.content);
  231.       var subject = new LiveTitleNotificationSubject(bookmarkID, microsummary);
  232.       LOG("updated live title for " + bookmarkIdentity +
  233.           " from '" + (title == null ? "<no live title>" : title) +
  234.           "' to '" + microsummary.content + "'");
  235.       this._obs.notifyObservers(subject, "microsummary-livetitle-updated", title);
  236.     }
  237.     else {
  238.       LOG("didn't update live title for " + bookmarkIdentity + "; it hasn't changed");
  239.     }
  240.  
  241.     // Whether or not the title itself has changed, we still save any changes
  242.     // to the update interval, since the interval represents how long to wait
  243.     // before checking again for updates, and that can vary across updates,
  244.     // even when the title itself hasn't changed.
  245.     this._setAnnotation(bookmarkID, ANNO_MICSUM_EXPIRATION,
  246.                   Date.now() + (microsummary.updateInterval || this._updateInterval));
  247.   },
  248.  
  249.   /**
  250.    * Load local generators into the cache.
  251.    * 
  252.    */
  253.   _cacheLocalGenerators: function MSS__cacheLocalGenerators() {
  254.     // Load generators from the application directory.
  255.     var appDir = this._dirs.get("MicsumGens", Ci.nsIFile);
  256.     if (appDir.exists())
  257.       this._cacheLocalGeneratorDir(appDir);
  258.  
  259.     // Load generators from the user's profile.
  260.     var profileDir = this._dirs.get("UsrMicsumGens", Ci.nsIFile);
  261.     if (profileDir.exists())
  262.       this._cacheLocalGeneratorDir(profileDir);
  263.   },
  264.  
  265.   /**
  266.    * Load local generators from a directory into the cache.
  267.    *
  268.    * @param   dir
  269.    *          nsIFile object pointing to directory containing generator files
  270.    * 
  271.    */
  272.   _cacheLocalGeneratorDir: function MSS__cacheLocalGeneratorDir(dir) {
  273.     var files = dir.directoryEntries.QueryInterface(Ci.nsIDirectoryEnumerator);
  274.     var file = files.nextFile;
  275.  
  276.     while (file) {
  277.       // Recursively load generators so support packs containing
  278.       // lots of generators can organize them into multiple directories.
  279.       if (file.isDirectory())
  280.         this._cacheLocalGeneratorDir(file);
  281.       else
  282.         this._cacheLocalGeneratorFile(file);
  283.  
  284.       file = files.nextFile;
  285.     }
  286.     files.close();
  287.   },
  288.  
  289.   /**
  290.    * Load a local generator from a file into the cache.
  291.    * 
  292.    * @param   file
  293.    *          nsIFile object pointing to file from which to load generator
  294.    * 
  295.    */
  296.   _cacheLocalGeneratorFile: function MSS__cacheLocalGeneratorFile(file) {
  297.     var uri = this._ios.newFileURI(file);
  298.  
  299.     var t = this;
  300.     var callback =
  301.       function MSS_cacheLocalGeneratorCallback(resource) {
  302.         try     { t._handleLocalGenerator(resource) }
  303.         finally { resource.destroy() }
  304.       };
  305.  
  306.     var resource = new MicrosummaryResource(uri);
  307.     resource.load(callback);
  308.   },
  309.  
  310.   _handleLocalGenerator: function MSS__handleLocalGenerator(resource) {
  311.     if (!resource.isXML)
  312.       throw(resource.uri.spec + " microsummary generator loaded, but not XML");
  313.  
  314.     var generator = new MicrosummaryGenerator(null, resource.uri);
  315.     generator.initFromXML(resource.content);
  316.  
  317.     // Add the generator to the local generators cache.
  318.     // XXX Figure out why Firefox crashes on shutdown if we index generators
  319.     // by uri.spec but doesn't crash if we index by uri.spec.split().join().
  320.     //this._localGenerators[generator.uri.spec] = generator;
  321.     this._localGenerators[generator.uri.spec.split().join()] = generator;
  322.  
  323.     LOG("loaded local microsummary generator\n" +
  324.         "  file: " + generator.localURI.spec + "\n" +
  325.         "    ID: " + generator.uri.spec);
  326.   },
  327.  
  328.   // nsIMicrosummaryService
  329.  
  330.   /**
  331.    * Return a microsummary generator for the given URI.
  332.    *
  333.    * @param   generatorURI
  334.    *          the URI of the generator
  335.    */
  336.   getGenerator: function MSS_getGenerator(generatorURI) {
  337.     return this._localGenerators[generatorURI.spec] ||
  338.       new MicrosummaryGenerator(generatorURI);
  339.   },
  340.  
  341.   /**
  342.    * Install the microsummary generator from the resource at the supplied URI.
  343.    * Callable by content via the addMicrosummaryGenerator() sidebar method.
  344.    *
  345.    * @param   generatorURI
  346.    *          the URI of the resource providing the generator
  347.    *
  348.    */
  349.   addGenerator: function MSS_addGenerator(generatorURI) {
  350.     var t = this;
  351.     var callback =
  352.       function MSS_addGeneratorCallback(resource) {
  353.         try     { t._handleNewGenerator(resource) }
  354.         finally { resource.destroy() }
  355.       };
  356.  
  357.     var resource = new MicrosummaryResource(generatorURI);
  358.     resource.load(callback);
  359.   },
  360.  
  361.   _handleNewGenerator: function MSS__handleNewGenerator(resource) {
  362.     if (!resource.isXML)
  363.       throw(resource.uri.spec + " microsummary generator loaded, but not XML");
  364.  
  365.     // XXX Make sure it's a valid microsummary generator.
  366.  
  367.     var rootNode = resource.content.documentElement;
  368.  
  369.     // Add a reference to the URI from which we got this generator so we have
  370.     // a unique identifier for the generator and also so we can check back later
  371.     // for updates.
  372.     rootNode.setAttribute("uri", "urn:source:" + resource.uri.spec);
  373.  
  374.     this.installGenerator(resource.content);
  375.   },
  376.  
  377.   /**
  378.    * Install a microsummary generator from the given XML definition.
  379.    *
  380.    * @param   xmlDefinition
  381.    *          an nsIDOMDocument XML document defining the generator
  382.    *
  383.    * @returns the newly-installed nsIMicrosummaryGenerator generator
  384.    *
  385.    */
  386.   installGenerator: function MSS_installGenerator(xmlDefinition) {
  387.     var rootNode = xmlDefinition.getElementsByTagNameNS(MICSUM_NS, "generator")[0];
  388.  
  389.     var generatorID = rootNode.getAttribute("uri");
  390.  
  391.     // The existing cache entry for this generator, if it is already installed.
  392.     var generator = this._localGenerators[generatorID];
  393.  
  394.     var topic;
  395.     if (generator)
  396.       topic = "microsummary-generator-updated";
  397.     else {
  398.       // This generator is not already installed.  Save it as a new file.
  399.       topic = "microsummary-generator-installed";
  400.       var generatorName = rootNode.getAttribute("name");
  401.       var fileName = sanitizeName(generatorName) + ".xml";
  402.       var file = this._dirs.get("UsrMicsumGens", Ci.nsIFile);
  403.       file.append(fileName);
  404.       file.createUnique(Ci.nsIFile.NORMAL_FILE_TYPE, PERMS_FILE);
  405.       generator = new MicrosummaryGenerator(null, this._ios.newFileURI(file));
  406.       this._localGenerators[generatorID] = generator;
  407.     }
  408.  
  409.     // Initialize (or reinitialize) the generator from its XML definition,
  410.     // the save the definition to the generator's file.
  411.     generator.initFromXML(xmlDefinition);
  412.     generator.saveXMLToFile(xmlDefinition);
  413.  
  414.     LOG("installed generator " + generatorID);
  415.  
  416.     this._obs.notifyObservers(generator, topic, null);
  417.  
  418.     return generator;
  419.   },
  420.  
  421.   /**
  422.    * Get the set of microsummaries available for a given page.  The set
  423.    * might change after this method returns, since this method will trigger
  424.    * an asynchronous load of the page in question (if it isn't already loaded)
  425.    * to see if it references any page-specific microsummaries.
  426.    *
  427.    * If the caller passes a bookmark ID, and one of the microsummaries
  428.    * is the current one for the bookmark, this method will retrieve content
  429.    * from the datastore for that microsummary, which is useful when callers
  430.    * want to display a list of microsummaries for a page that isn't loaded,
  431.    * and they want to display the actual content of the selected microsummary
  432.    * immediately (rather than after the content is asynchronously loaded).
  433.    *
  434.    * @param   pageURI
  435.    *          the URI of the page for which to retrieve available microsummaries
  436.    *
  437.    * @param   bookmarkID (optional)
  438.    *          the ID of the bookmark for which this method is being called
  439.    *
  440.    * @returns an nsIMicrosummarySet of nsIMicrosummaries for the given page
  441.    *
  442.    */
  443.   getMicrosummaries: function MSS_getMicrosummaries(pageURI, bookmarkID) {
  444.     var microsummaries = new MicrosummarySet();
  445.  
  446.     if (!getPref("browser.microsummary.enabled", true))
  447.       return microsummaries;
  448.  
  449.     // Get microsummaries defined by local generators.
  450.     for (var genURISpec in this._localGenerators) {
  451.       var generator = this._localGenerators[genURISpec];
  452.  
  453.       if (generator.appliesToURI(pageURI)) {
  454.         var microsummary = new Microsummary(pageURI, generator);
  455.  
  456.         // If this is the current microsummary for this bookmark, load the content
  457.         // from the datastore so it shows up immediately in microsummary picking UI.
  458.         if (bookmarkID != -1 && this.isMicrosummary(bookmarkID, microsummary))
  459.           microsummary._content = this._bms.getItemTitle(bookmarkID);
  460.  
  461.         microsummaries.AppendElement(microsummary);
  462.       }
  463.     }
  464.  
  465.     // If a bookmark identifier has been provided, list its microsummary
  466.     // synchronously, if any.
  467.     if (bookmarkID != -1 && this.hasMicrosummary(bookmarkID)) {
  468.       var currentMicrosummary = this.getMicrosummary(bookmarkID);
  469.       if (!microsummaries.hasItemForMicrosummary(currentMicrosummary))
  470.         microsummaries.AppendElement(currentMicrosummary);
  471.     }
  472.  
  473.     // Get microsummaries defined by the page.  If we don't have the page,
  474.     // download it asynchronously, and then finish populating the set.
  475.     var resource = getLoadedMicrosummaryResource(pageURI);
  476.     if (resource) {
  477.       try     { microsummaries.extractFromPage(resource) }
  478.       finally { resource.destroy() }
  479.     }
  480.     else {
  481.       // Load the page with a callback that will add the page's microsummaries
  482.       // to the set once the page has loaded.
  483.       var callback = function MSS_extractFromPageCallback(resource) {
  484.         try     { microsummaries.extractFromPage(resource) }
  485.         finally { resource.destroy() }
  486.       };
  487.  
  488.       try {
  489.         resource = new MicrosummaryResource(pageURI);
  490.         resource.load(callback);
  491.       }
  492.       catch(e) {
  493.         // We don't have to do anything special if the call fails besides
  494.         // destroying the Resource object.  We can just return the list
  495.         // of microsummaries without including page-defined microsummaries.
  496.         if (resource)
  497.           resource.destroy();
  498.         LOG("error downloading page to extract its microsummaries: " + e);
  499.       }
  500.     }
  501.  
  502.     return microsummaries;
  503.   },
  504.  
  505.   /**
  506.    * Change all occurrences of a specific value in a given field to a new value.
  507.    *
  508.    * @param   fieldName
  509.    *          the name of the field whose values should be changed
  510.    * @param   oldValue
  511.    *          the value that should be changed
  512.    * @param   newValue
  513.    *          the value to which it should be changed
  514.    *
  515.    */
  516.   _changeField: function MSS__changeField(fieldName, oldValue, newValue) {
  517.     var bookmarks = this._getBookmarks();
  518.  
  519.     for ( var i = 0; i < bookmarks.length; i++ ) {
  520.       var bookmarkID = bookmarks[i];
  521.  
  522.       if (this._ans.itemHasAnnotation(bookmarkID, fieldName) &&
  523.           this._ans.getItemAnnotation(bookmarkID, fieldName) == oldValue)
  524.         this._setAnnotation(bookmarkID, fieldName, newValue);
  525.     }
  526.   },
  527.  
  528.   /**
  529.    * Get the set of bookmarks with microsummaries.
  530.    *
  531.    * This is the internal version of this method, which is not accessible
  532.    * via XPCOM but is more performant; inside this component, use this version.
  533.    * Outside the component, use getBookmarks (no underscore prefix) instead.
  534.    *
  535.    * @returns an array of place: uris representing bookmarks items
  536.    *
  537.    */
  538.   _getBookmarks: function MSS__getBookmarks() {
  539.     var bookmarks;
  540.  
  541.     // This try/catch block is a temporary workaround for bug 336194.
  542.     try {
  543.       bookmarks = this._ans.getItemsWithAnnotation(ANNO_MICSUM_GEN_URI, {});
  544.     }
  545.     catch(e) {
  546.       bookmarks = [];
  547.     }
  548.  
  549.     return bookmarks;
  550.   },
  551.  
  552.   _setAnnotation: function MSS__setAnnotation(aBookmarkId, aFieldName, aFieldValue) {
  553.     this._ans.setItemAnnotation(aBookmarkId,
  554.                                 aFieldName,
  555.                                 aFieldValue,
  556.                                 0,
  557.                                 this._ans.EXPIRE_NEVER);
  558.   },
  559.  
  560.   /**
  561.    * Get the set of bookmarks with microsummaries.
  562.    *
  563.    * This is the external version of this method and is accessible via XPCOM.
  564.    * Use it outside this component. Inside the component, use _getBookmarks
  565.    * (with underscore prefix) instead for performance.
  566.    *
  567.    * @returns an nsISimpleEnumerator enumeration of bookmark IDs
  568.    *
  569.    */
  570.   getBookmarks: function MSS_getBookmarks() {
  571.     return new ArrayEnumerator(this._getBookmarks());
  572.   },
  573.  
  574.   /**
  575.    * Get the current microsummary for the given bookmark.
  576.    *
  577.    * @param   bookmarkID
  578.    *          the bookmark for which to get the current microsummary
  579.    *
  580.    * @returns the current microsummary for the bookmark, or null
  581.    *          if the bookmark does not have a current microsummary
  582.    *
  583.    */
  584.   getMicrosummary: function MSS_getMicrosummary(bookmarkID) {
  585.     if (!this.hasMicrosummary(bookmarkID))
  586.       return null;
  587.  
  588.     var pageURI = this._bms.getBookmarkURI(bookmarkID);
  589.     var generatorURI = this._uri(this._ans.getItemAnnotation(bookmarkID,
  590.                                                              ANNO_MICSUM_GEN_URI));
  591.     var generator = this.getGenerator(generatorURI);
  592.  
  593.     return new Microsummary(pageURI, generator);
  594.   },
  595.  
  596.   /**
  597.    * Get a microsummary for a given page URI and generator URI.
  598.    *
  599.    * @param   pageURI
  600.    *          the URI of the page to be summarized
  601.    *
  602.    * @param   generatorURI
  603.    *          the URI of the microsummary generator
  604.    *
  605.    * @returns an nsIMicrosummary for the given page and generator URIs.
  606.    *
  607.    */
  608.   createMicrosummary: function MSS_createMicrosummary(pageURI, generatorURI) {
  609.     var generator = this.getGenerator(generatorURI);
  610.     return new Microsummary(pageURI, generator);
  611.   },
  612.  
  613.   /**
  614.    * Set the current microsummary for the given bookmark.
  615.    *
  616.    * @param   bookmarkID
  617.    *          the bookmark for which to set the current microsummary
  618.    *
  619.    * @param   microsummary
  620.    *          the microsummary to set as the current one
  621.    *
  622.    */
  623.   setMicrosummary: function MSS_setMicrosummary(bookmarkID, microsummary) {
  624.     this._setAnnotation(bookmarkID, ANNO_MICSUM_GEN_URI, microsummary.generator.uri.spec);
  625.  
  626.     if (microsummary.content)
  627.       this._updateMicrosummary(bookmarkID, microsummary);
  628.     else
  629.       this.refreshMicrosummary(bookmarkID);
  630.   },
  631.  
  632.   /**
  633.    * Remove the current microsummary for the given bookmark.
  634.    *
  635.    * @param   bookmarkID
  636.    *          the bookmark for which to remove the current microsummary
  637.    *
  638.    */
  639.   removeMicrosummary: function MSS_removeMicrosummary(bookmarkID) {
  640.     // Restore the user's title
  641.     if (this._ans.itemHasAnnotation(bookmarkID, ANNO_STATIC_TITLE))
  642.       this._bms.setItemTitle(bookmarkID, this._ans.getItemAnnotation(bookmarkID, ANNO_STATIC_TITLE));
  643.  
  644.     var fields = [ANNO_MICSUM_GEN_URI,
  645.                   ANNO_MICSUM_EXPIRATION,
  646.                   ANNO_STATIC_TITLE,
  647.                   ANNO_CONTENT_TYPE];
  648.  
  649.     for (let i = 0; i < fields.length; i++) {
  650.       var field = fields[i];
  651.       if (this._ans.itemHasAnnotation(bookmarkID, field))
  652.         this._ans.removeItemAnnotation(bookmarkID, field);
  653.     }
  654.   },
  655.  
  656.   /**
  657.    * Whether or not the given bookmark has a current microsummary.
  658.    *
  659.    * @param   bookmarkID
  660.    *          the bookmark for which to set the current microsummary
  661.    *
  662.    * @returns a boolean representing whether or not the given bookmark
  663.    *          has a current microsummary
  664.    *
  665.    */
  666.   hasMicrosummary: function MSS_hasMicrosummary(bookmarkID) {
  667.     return this._ans.itemHasAnnotation(bookmarkID, ANNO_MICSUM_GEN_URI);
  668.   },
  669.  
  670.   /**
  671.    * Whether or not the given microsummary is the current microsummary
  672.    * for the given bookmark.
  673.    *
  674.    * @param   bookmarkID
  675.    *          the bookmark to check
  676.    *
  677.    * @param   microsummary
  678.    *          the microsummary to check
  679.    *
  680.    * @returns whether or not the microsummary is the current one
  681.    *          for the bookmark
  682.    *
  683.    */
  684.   isMicrosummary: function MSS_isMicrosummary(aBookmarkID, aMicrosummary) {
  685.     if (!aMicrosummary || !aBookmarkID)
  686.       throw Cr.NS_ERROR_INVALID_ARG;
  687.  
  688.     if (this.hasMicrosummary(aBookmarkID)) {
  689.       currentMicrosummarry = this.getMicrosummary(aBookmarkID);
  690.       if (aMicrosummary.equals(currentMicrosummarry))
  691.         return true;
  692.     }
  693.     return false
  694.   },
  695.  
  696.   /**
  697.    * Refresh a microsummary, updating its value in the datastore and UI.
  698.    * If this method can refresh the microsummary instantly, it will.
  699.    * Otherwise, it'll asynchronously download the necessary information
  700.    * (the generator and/or page) before refreshing the microsummary.
  701.    *
  702.    * Callers should check the "content" property of the returned microsummary
  703.    * object to distinguish between sync and async refreshes.  If its value
  704.    * is "null", then it's an async refresh, and the caller should register
  705.    * itself as an nsIMicrosummaryObserver via nsIMicrosummary.addObserver()
  706.    * to find out when the refresh completes.
  707.    *
  708.    * @param   bookmarkID
  709.    *          the bookmark whose microsummary is being refreshed
  710.    *
  711.    * @returns the microsummary being refreshed
  712.    *
  713.    */
  714.   refreshMicrosummary: function MSS_refreshMicrosummary(bookmarkID) {
  715.     if (!this.hasMicrosummary(bookmarkID))
  716.       throw "bookmark " + bookmarkID + " does not have a microsummary";
  717.  
  718.     var pageURI = this._bms.getBookmarkURI(bookmarkID);
  719.     if (!pageURI)
  720.       throw("can't get URL for bookmark with ID " + bookmarkID);
  721.     var generatorURI = this._uri(this._ans.getItemAnnotation(bookmarkID,
  722.                                                              ANNO_MICSUM_GEN_URI));
  723.  
  724.     var generator = this._localGenerators[generatorURI.spec] ||
  725.                     new MicrosummaryGenerator(generatorURI);
  726.  
  727.     var microsummary = new Microsummary(pageURI, generator);
  728.  
  729.     // A microsummary observer that calls the microsummary service
  730.     // to update the datastore when the microsummary finishes loading.
  731.     var observer = {
  732.       _svc: this,
  733.       _bookmarkID: bookmarkID,
  734.       onContentLoaded: function MSS_observer_onContentLoaded(microsummary) {
  735.         try {
  736.           this._svc._updateMicrosummary(this._bookmarkID, microsummary);
  737.         }
  738.         finally {
  739.           this._svc = null;
  740.           this._bookmarkID = null;
  741.           microsummary.removeObserver(this);
  742.         }
  743.       },
  744.  
  745.       onError: function MSS_observer_onError(microsummary) {
  746.         if (microsummary.needsRemoval)
  747.           this._svc.removeMicrosummary(this._bookmarkID);
  748.       }
  749.     };
  750.  
  751.     // Register the observer with the microsummary and trigger the microsummary
  752.     // to update itself.
  753.     microsummary.addObserver(observer);
  754.     microsummary.update();
  755.     
  756.     return microsummary;
  757.   }
  758. };
  759.  
  760.  
  761.  
  762.  
  763.  
  764. function LiveTitleNotificationSubject(bookmarkID, microsummary) {
  765.   this.bookmarkID = bookmarkID;
  766.   this.microsummary = microsummary;
  767. }
  768.  
  769. LiveTitleNotificationSubject.prototype = {
  770.   bookmarkID: null,
  771.   microsummary: null,
  772.  
  773.   // nsISupports
  774.   QueryInterface: XPCOMUtils.generateQI([Ci.nsILiveTitleNotificationSubject]),
  775. };
  776.  
  777.  
  778.  
  779.  
  780.  
  781. function Microsummary(aPageURI, aGenerator) {
  782.   this._observers = [];
  783.   this._pageURI = aPageURI || null;
  784.   this._generator = aGenerator || null;
  785.   this._content = null;
  786.   this._pageContent = null;
  787.   this._updateInterval = null;
  788.   this._needsRemoval = false;
  789. }
  790.  
  791. Microsummary.prototype = {
  792.   // The microsummary service.
  793.   __mss: null,
  794.   get _mss() {
  795.     if (!this.__mss)
  796.       this.__mss = Cc["@mozilla.org/microsummary/service;1"].
  797.                    getService(Ci.nsIMicrosummaryService);
  798.     return this.__mss;
  799.   },
  800.  
  801.   // IO Service
  802.   __ios: null,
  803.   get _ios() {
  804.     if (!this.__ios)
  805.       this.__ios = Cc["@mozilla.org/network/io-service;1"].
  806.                    getService(Ci.nsIIOService);
  807.     return this.__ios;
  808.   },
  809.  
  810.   /**
  811.    * Make a URI from a spec.
  812.    * @param   spec
  813.    *          The string spec of the URI.
  814.    * @returns An nsIURI object.
  815.    */
  816.   _uri: function MSS__uri(spec) {
  817.     return this._ios.newURI(spec, null, null);
  818.   },
  819.  
  820.   // nsISupports
  821.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIMicrosummary]),
  822.  
  823.   // nsIMicrosummary
  824.   get content() {
  825.     // If we have everything we need to generate the content, generate it.
  826.     if (!this._content &&
  827.         this.generator.loaded &&
  828.         (this.pageContent || !this.generator.needsPageContent)) {
  829.       this._content = this.generator.generateMicrosummary(this.pageContent);
  830.       this._updateInterval = this.generator.calculateUpdateInterval(this.pageContent);
  831.     }
  832.  
  833.     // Note: we return "null" if the content wasn't already generated and we
  834.     // couldn't retrieve it from the generated title annotation or generate it
  835.     // ourselves.  So callers shouldn't count on getting content; instead,
  836.     // they should call update if the return value of this getter is "null",
  837.     // setting an observer to tell them when content generation is done.
  838.     return this._content;
  839.   },
  840.  
  841.   get generator()            { return this._generator },
  842.   set generator(newValue)    { return this._generator = newValue },
  843.  
  844.   get pageURI() { return this._pageURI },
  845.  
  846.   equals: function(aOther) {
  847.     if (this._generator &&
  848.         this._pageURI.equals(aOther.pageURI) &&
  849.         this._generator.equals(aOther.generator))
  850.       return true;
  851.  
  852.     return false;
  853.   },
  854.  
  855.   get pageContent() {
  856.     if (!this._pageContent) {
  857.       // If the page is currently loaded into a browser window, use that.
  858.       var resource = getLoadedMicrosummaryResource(this.pageURI);
  859.       if (resource) {
  860.         this._pageContent = resource.content;
  861.         resource.destroy();
  862.       }
  863.     }
  864.  
  865.     return this._pageContent;
  866.   },
  867.   set pageContent(newValue) { return this._pageContent = newValue },
  868.  
  869.   get updateInterval()         { return this._updateInterval; },
  870.   set updateInterval(newValue) { return this._updateInterval = newValue; },
  871.  
  872.   get needsRemoval() { return this._needsRemoval; },
  873.  
  874.   // nsIMicrosummary
  875.  
  876.   addObserver: function MS_addObserver(observer) {
  877.     // Register the observer, but only if it isn't already registered,
  878.     // so that we don't call the same observer twice for any given change.
  879.     if (this._observers.indexOf(observer) == -1)
  880.       this._observers.push(observer);
  881.   },
  882.   
  883.   removeObserver: function MS_removeObserver(observer) {
  884.     //NS_ASSERT(this._observers.indexOf(observer) != -1,
  885.     //          "can't remove microsummary observer " + observer + ": not registered");
  886.   
  887.     //this._observers =
  888.     //  this._observers.filter(function(i) { observer != i });
  889.     if (this._observers.indexOf(observer) != -1)
  890.       this._observers.splice(this._observers.indexOf(observer), 1);
  891.   },
  892.  
  893.   /**
  894.    * Regenerates the microsummary, asynchronously downloading its generator
  895.    * and content as needed.
  896.    *
  897.    */
  898.   update: function MS_update() {
  899.     LOG("microsummary.update called for page:\n  " + this.pageURI.spec +
  900.         "\nwith generator:\n  " + this.generator.uri.spec);
  901.  
  902.     var t = this;
  903.  
  904.     // We use a common error callback here to flag this microsummary for removal
  905.     // if either the generator or page content have gone permanently missing.
  906.     var errorCallback = function MS_errorCallback(resource) {
  907.       if (resource.status == 410) {
  908.         t._needsRemoval = true;
  909.         LOG("server indicated " + resource.uri.spec + " is gone. flagging for removal");
  910.       }
  911.  
  912.       resource.destroy();
  913.  
  914.       for (let i = 0; i < t._observers.length; i++)
  915.         t._observers[i].onError(t);
  916.     };
  917.  
  918.     // If we don't have the generator, download it now.  After it downloads,
  919.     // we'll re-call this method to continue updating the microsummary.
  920.     if (!this.generator.loaded) {
  921.       // If this generator is identified by a URN, then it's a local generator
  922.       // that should have been cached on application start, so it's missing.
  923.       if (this.generator.uri.scheme == "urn") {
  924.         // If it was installed via nsSidebar::addMicrosummaryGenerator (i.e. it
  925.         // has a URN that identifies the source URL from which we installed it),
  926.         // try to reinstall it (once).
  927.         if (/^source:/.test(this.generator.uri.path)) {
  928.           this._reinstallMissingGenerator();
  929.           return;
  930.         }
  931.         else
  932.           throw "missing local generator: " + this.generator.uri.spec;
  933.       }
  934.  
  935.       LOG("generator not yet loaded; downloading it");
  936.       var generatorCallback =
  937.         function MS_generatorCallback(resource) {
  938.           try     { t._handleGeneratorLoad(resource) }
  939.           finally { resource.destroy() }
  940.         };
  941.       var resource = new MicrosummaryResource(this.generator.uri);
  942.       resource.load(generatorCallback, errorCallback);
  943.       return;
  944.     }
  945.  
  946.     // If we need the page content, and we don't have it, download it now.
  947.     // Afterwards we'll re-call this method to continue updating the microsummary.
  948.     if (this.generator.needsPageContent && !this.pageContent) {
  949.       LOG("page content not yet loaded; downloading it");
  950.       var pageCallback =
  951.         function MS_pageCallback(resource) {
  952.           try     { t._handlePageLoad(resource) }
  953.           finally { resource.destroy() }
  954.         };
  955.       var resource = new MicrosummaryResource(this.pageURI);
  956.       resource.load(pageCallback, errorCallback);
  957.       return;
  958.     }
  959.  
  960.     LOG("generator (and page, if needed) both loaded; generating microsummary");
  961.  
  962.     // Now that we have both the generator and (if needed) the page content,
  963.     // generate the microsummary, then let the observers know about it.
  964.     this._content = this.generator.generateMicrosummary(this.pageContent);
  965.     this._updateInterval = this.generator.calculateUpdateInterval(this.pageContent);
  966.     this.pageContent = null;
  967.     for ( var i = 0; i < this._observers.length; i++ )
  968.       this._observers[i].onContentLoaded(this);
  969.  
  970.     LOG("generated microsummary: " + this.content);
  971.   },
  972.  
  973.   _handleGeneratorLoad: function MS__handleGeneratorLoad(resource) {
  974.     LOG(this.generator.uri.spec + " microsummary generator downloaded");
  975.     if (resource.isXML)
  976.       this.generator.initFromXML(resource.content);
  977.     else if (resource.contentType == "text/plain")
  978.       this.generator.initFromText(resource.content);
  979.     else if (resource.contentType == "text/html")
  980.       this.generator.initFromText(resource.content.body.textContent);
  981.     else
  982.       throw("generator is neither XML nor plain text");
  983.  
  984.     // Only trigger a [content] update if we were able to init the generator. 
  985.     if (this.generator.loaded)
  986.       this.update();
  987.   },
  988.  
  989.   _handlePageLoad: function MS__handlePageLoad(resource) {
  990.     if (!resource.isXML && resource.contentType != "text/html")
  991.       throw("page is neither HTML nor XML");
  992.  
  993.     this.pageContent = resource.content;
  994.     this.update();
  995.   },
  996.  
  997.   /**
  998.    * Try to reinstall a missing local generator that was originally installed
  999.    * from a URL using nsSidebar::addMicrosumaryGenerator.
  1000.    *
  1001.    */
  1002.   _reinstallMissingGenerator: function MS__reinstallMissingGenerator() {
  1003.     LOG("attempting to reinstall missing generator " + this.generator.uri.spec);
  1004.  
  1005.     var t = this;
  1006.  
  1007.     var loadCallback =
  1008.       function MS_missingGeneratorLoadCallback(resource) {
  1009.         try     { t._handleMissingGeneratorLoad(resource) }
  1010.         finally { resource.destroy() }
  1011.       };
  1012.  
  1013.     var errorCallback =
  1014.       function MS_missingGeneratorErrorCallback(resource) {
  1015.         try     { t._handleMissingGeneratorError(resource) }
  1016.         finally { resource.destroy() }
  1017.       };
  1018.  
  1019.     try {
  1020.       // Extract the URI from which the generator was originally installed.
  1021.       var sourceURL = this.generator.uri.path.replace(/^source:/, "");
  1022.       var sourceURI = this._uri(sourceURL);
  1023.  
  1024.       var resource = new MicrosummaryResource(sourceURI);
  1025.       resource.load(loadCallback, errorCallback);
  1026.     }
  1027.     catch(ex) {
  1028.       Cu.reportError(ex);
  1029.       this._handleMissingGeneratorError();
  1030.     }
  1031.   },
  1032.  
  1033.   /**
  1034.    * Handle a load event for a missing local generator by trying to reinstall
  1035.    * the generator.  If this fails, call _handleMissingGeneratorError to unset
  1036.    * microsummaries for bookmarks using this generator so we don't repeatedly
  1037.    * try to reinstall the generator, creating too much traffic to the website
  1038.    * from which we downloaded it.
  1039.    *
  1040.    * @param resource
  1041.    *        the nsIMicrosummaryResource representing the downloaded generator
  1042.    *
  1043.    */
  1044.   _handleMissingGeneratorLoad: function MS__handleMissingGeneratorLoad(resource) {
  1045.     try {
  1046.       // Make sure the generator is XML, since local generators have to be.
  1047.       if (!resource.isXML)
  1048.         throw("downloaded, but not XML " + this.generator.uri.spec);
  1049.  
  1050.       // Store the generator's ID in its XML definition.
  1051.       var generatorID = this.generator.uri.spec;
  1052.       resource.content.documentElement.setAttribute("uri", generatorID);
  1053.  
  1054.       // Reinstall the generator and replace our placeholder generator object
  1055.       // with the newly installed generator.
  1056.       this.generator = this._mss.installGenerator(resource.content);
  1057.  
  1058.       // A reinstalled generator should always be loaded.  But just in case
  1059.       // it isn't, throw an error so we don't get into an infinite loop
  1060.       // (otherwise this._update would try again to reinstall it).
  1061.       if (!this.generator.loaded)
  1062.         throw("supposedly installed, but not in cache " + this.generator.uri.spec);
  1063.     }
  1064.     catch(ex) {
  1065.       Cu.reportError(ex);
  1066.       this._handleMissingGeneratorError(resource);
  1067.       return;
  1068.     }
  1069.   
  1070.     LOG("reinstall succeeded; resuming update " + this.generator.uri.spec);
  1071.     this.update();
  1072.   },
  1073.  
  1074.   /**
  1075.    * Handle an error event for a missing local generator load by unsetting
  1076.    * the microsummaries for bookmarks using this generator so we don't
  1077.    * repeatedly try to reinstall the generator, creating too much traffic
  1078.    * to the website from which we downloaded it.
  1079.    *
  1080.    * @param resource
  1081.    *        the nsIMicrosummaryResource representing the downloaded generator
  1082.    *
  1083.    */
  1084.   _handleMissingGeneratorError: function MS__handleMissingGeneratorError(resource) {
  1085.     LOG("reinstall failed; removing microsummaries " + this.generator.uri.spec);
  1086.     var bookmarks = this._mss.getBookmarks();
  1087.     while (bookmarks.hasMoreElements()) {
  1088.       var bookmarkID = bookmarks.getNext();
  1089.       var microsummary = this._mss.getMicrosummary(bookmarkID);
  1090.       if (microsummary.generator.uri.equals(this.generator.uri)) {
  1091.         LOG("removing microsummary for " + microsummary.pageURI.spec);
  1092.         this._mss.removeMicrosummary(bookmarkID);
  1093.       }
  1094.     }
  1095.   }
  1096.  
  1097. };
  1098.  
  1099.  
  1100.  
  1101.  
  1102.  
  1103. function MicrosummaryGenerator(aURI, aLocalURI, aName) {
  1104.   this._uri = aURI || null;
  1105.   this._localURI = aLocalURI || null;
  1106.   this._name = aName || null;
  1107.   this._loaded = false;
  1108.   this._rules = [];
  1109.   this._template = null;
  1110.   this._content = null;
  1111. }
  1112.  
  1113. MicrosummaryGenerator.prototype = {
  1114.  
  1115.   // IO Service
  1116.   __ios: null,
  1117.   get _ios() {
  1118.     if (!this.__ios)
  1119.       this.__ios = Cc["@mozilla.org/network/io-service;1"].
  1120.                    getService(Ci.nsIIOService);
  1121.     return this.__ios;
  1122.   },
  1123.  
  1124.   // nsISupports
  1125.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIMicrosummaryGenerator]),
  1126.  
  1127.   // nsIMicrosummaryGenerator
  1128.  
  1129.   // Normally this is just the URL from which we download the generator,
  1130.   // but for generators stored in the app or profile generators directory
  1131.   // it's the value of the generator tag's "uri" attribute (or its local URI
  1132.   // should the "uri" attribute be missing).
  1133.   get uri() { return this._uri || this.localURI },
  1134.  
  1135.   // For generators bundled with the browser or installed by the user,
  1136.   // the local URI is the URI of the local file containing the generator XML.
  1137.   get localURI() { return this._localURI },
  1138.   get name() { return this._name },
  1139.   get loaded() { return this._loaded },
  1140.  
  1141.   equals: function(aOther) {
  1142.     // XXX: could the uri attribute for an exposed generator ever be null?
  1143.     return aOther.uri.equals(this.uri);
  1144.   },
  1145.  
  1146.   /**
  1147.    * Determines whether or not the generator applies to a given URI.
  1148.    * By default, the generator does not apply to any URI.  In order for it
  1149.    * to apply to a URI, the URI must match one or more of the generator's
  1150.    * "include" rules and not match any of the generator's "exclude" rules.
  1151.    *
  1152.    * @param   uri
  1153.    *          the URI to test to see if this generator applies to it
  1154.    *
  1155.    * @returns boolean
  1156.    *          whether or not the generator applies to the given URI
  1157.    *
  1158.    */
  1159.   appliesToURI: function(uri) {
  1160.     var applies = false;
  1161.  
  1162.     for ( var i = 0 ; i < this._rules.length ; i++ ) {
  1163.       var rule = this._rules[i];
  1164.  
  1165.       switch (rule.type) {
  1166.       case "include":
  1167.         if (rule.regexp.test(uri.spec))
  1168.           applies = true;
  1169.         break;
  1170.       case "exclude":
  1171.         if (rule.regexp.test(uri.spec))
  1172.           return false;
  1173.         break;
  1174.       }
  1175.     }
  1176.  
  1177.     return applies;
  1178.   },
  1179.  
  1180.   get needsPageContent() {
  1181.     if (this._template)
  1182.       return true;
  1183.     if (this._content)
  1184.       return false;
  1185.  
  1186.     throw("needsPageContent called on uninitialized microsummary generator");
  1187.   },
  1188.  
  1189.   /**
  1190.    * Initializes a generator from text content.  Generators initialized
  1191.    * from text content merely return that content when their generate() method
  1192.    * gets called.
  1193.    *
  1194.    * @param   text
  1195.    *          the text content
  1196.    */
  1197.   initFromText: function(text) {
  1198.     this._content = text;
  1199.     this._loaded = true;
  1200.   },
  1201.  
  1202.   /**
  1203.    * Initializes a generator from an XML description of it.
  1204.    * 
  1205.    * @param   xmlDocument
  1206.    *          An XMLDocument object describing a microsummary generator.
  1207.    *
  1208.    */
  1209.   initFromXML: function(xmlDocument) {
  1210.     // XXX Make sure the argument is a valid generator XML document.
  1211.  
  1212.     // XXX I would have wanted to retrieve the info from the XML via E4X,
  1213.     // but we'll need to pass the XSLT transform sheet to the XSLT processor,
  1214.     // and the processor can't deal with an E4X-wrapped template node.
  1215.  
  1216.     // XXX Right now the code retrieves the first "generator" element
  1217.     // in the microsummaries namespace, regardless of whether or not
  1218.     // it's the root element.  Should it matter?
  1219.     var generatorNode = xmlDocument.getElementsByTagNameNS(MICSUM_NS, "generator")[0];
  1220.     if (!generatorNode)
  1221.       throw Cr.NS_ERROR_FAILURE;
  1222.  
  1223.     this._name = generatorNode.getAttribute("name");
  1224.  
  1225.     // We have to retrieve the URI from local generators via the "uri" attribute
  1226.     // of its generator tag.
  1227.     if (this.localURI && generatorNode.hasAttribute("uri"))
  1228.       this._uri = this._ios.newURI(generatorNode.getAttribute("uri"), null, null);
  1229.  
  1230.     function getFirstChildByTagName(tagName, parentNode, namespace) {
  1231.       var nodeList = parentNode.getElementsByTagNameNS(namespace, tagName);
  1232.       for (var i = 0; i < nodeList.length; i++) {
  1233.         // Make sure that the node is a direct descendent of the generator node
  1234.         if (nodeList[i].parentNode == parentNode)
  1235.           return nodeList[i];
  1236.       }
  1237.       return null;
  1238.     }
  1239.  
  1240.     // Slurp the include/exclude rules that determine the pages to which
  1241.     // this generator applies.  Order is important, so we add the rules
  1242.     // in the order in which they appear in the XML.
  1243.     this._rules.splice(0);
  1244.     var pages = getFirstChildByTagName("pages", generatorNode, MICSUM_NS);
  1245.     if (pages) {
  1246.       // XXX Make sure the pages tag exists.
  1247.       for ( var i = 0; i < pages.childNodes.length ; i++ ) {
  1248.         var node = pages.childNodes[i];
  1249.         if (node.nodeType != node.ELEMENT_NODE ||
  1250.             node.namespaceURI != MICSUM_NS ||
  1251.             (node.nodeName != "include" && node.nodeName != "exclude"))
  1252.           continue;
  1253.         var urlRegexp = node.textContent.replace(/^\s+|\s+$/g, "");
  1254.         this._rules.push({ type: node.nodeName, regexp: new RegExp(urlRegexp) });
  1255.       }
  1256.     }
  1257.  
  1258.     // allow the generators to set individual update values (even varying
  1259.     // depending on certain XPath expressions)
  1260.     var update = getFirstChildByTagName("update", generatorNode, MICSUM_NS);
  1261.     if (update) {
  1262.       function _parseInterval(string) {
  1263.         // convert from minute fractions to milliseconds
  1264.         // and ensure a minimum value of 1 minute
  1265.         return Math.round(Math.max(parseFloat(string) || 0, 1) * 60 * 1000);
  1266.       }
  1267.  
  1268.       this._unconditionalUpdateInterval =
  1269.         update.hasAttribute("interval") ?
  1270.         _parseInterval(update.getAttribute("interval")) : null;
  1271.  
  1272.       // collect the <condition expression="XPath Expression" interval="time"/> clauses
  1273.       this._updateIntervals = new Array();
  1274.       for (i = 0; i < update.childNodes.length; i++) {
  1275.         node = update.childNodes[i];
  1276.         if (node.nodeType != node.ELEMENT_NODE || node.namespaceURI != MICSUM_NS ||
  1277.             node.nodeName != "condition")
  1278.           continue;
  1279.         if (!node.getAttribute("expression") || !node.getAttribute("interval")) {
  1280.           LOG("ignoring incomplete conditional update interval for " + this.uri.spec);
  1281.           continue;
  1282.         }
  1283.         this._updateIntervals.push({
  1284.           expression: node.getAttribute("expression"),
  1285.           interval: _parseInterval(node.getAttribute("interval"))
  1286.         });
  1287.       }
  1288.     }
  1289.  
  1290.     var templateNode = getFirstChildByTagName("template", generatorNode, MICSUM_NS);
  1291.     if (templateNode) {
  1292.       this._template = getFirstChildByTagName("transform", templateNode, XSLT_NS) ||
  1293.                        getFirstChildByTagName("stylesheet", templateNode, XSLT_NS);
  1294.     }
  1295.     // XXX Make sure the template is a valid XSL transform sheet.
  1296.  
  1297.     this._loaded = true;
  1298.   },
  1299.  
  1300.   generateMicrosummary: function MSD_generateMicrosummary(pageContent) {
  1301.  
  1302.     var content;
  1303.  
  1304.     if (this._content)
  1305.       content = this._content;
  1306.     else if (this._template)
  1307.       content = this._processTemplate(pageContent);
  1308.     else
  1309.       throw("generateMicrosummary called on uninitialized microsummary generator");
  1310.  
  1311.     // Clean up the output
  1312.     content = content.replace(/^\s+|\s+$/g, "");
  1313.     if (content.length > MAX_SUMMARY_LENGTH) 
  1314.       content = content.substring(0, MAX_SUMMARY_LENGTH);
  1315.  
  1316.     return content;
  1317.   },
  1318.  
  1319.   calculateUpdateInterval: function MSD_calculateUpdateInterval(doc) {
  1320.     if (this._content || !this._updateIntervals || !doc)
  1321.       return null;
  1322.  
  1323.     for (var i = 0; i < this._updateIntervals.length; i++) {
  1324.       try {
  1325.         if (doc.evaluate(this._updateIntervals[i].expression, doc, null,
  1326.                          Ci.nsIDOMXPathResult.BOOLEAN_TYPE, null).booleanValue)
  1327.           return this._updateIntervals[i].interval;
  1328.       }
  1329.       catch (ex) {
  1330.         Cu.reportError(ex);
  1331.         // remove the offending conditional update interval
  1332.         this._updateIntervals.splice(i--, 1);
  1333.       }
  1334.     }
  1335.  
  1336.     return this._unconditionalUpdateInterval;
  1337.   },
  1338.  
  1339.   _processTemplate: function MSD__processTemplate(doc) {
  1340.     LOG("processing template " + this._template + " against document " + doc);
  1341.  
  1342.     // XXX Should we just have one global instance of the processor?
  1343.     var processor = Cc["@mozilla.org/document-transformer;1?type=xslt"].
  1344.                     createInstance(Ci.nsIXSLTProcessor);
  1345.  
  1346.     // Turn off document loading of all kinds (document(), <include>, <import>)
  1347.     // for security (otherwise local generators would be able to load local files).
  1348.     processor.flags |= Ci.nsIXSLTProcessorPrivate.DISABLE_ALL_LOADS;
  1349.  
  1350.     processor.importStylesheet(this._template);
  1351.     var fragment = processor.transformToFragment(doc, doc);
  1352.  
  1353.     LOG("template processing result: " + fragment.textContent);
  1354.  
  1355.     // XXX When we support HTML microsummaries we'll need to do something
  1356.     // more sophisticated than just returning the text content of the fragment.
  1357.     return fragment.textContent;
  1358.   },
  1359.  
  1360.   saveXMLToFile: function MSD_saveXMLToFile(xmlDefinition) {
  1361.     var file = this.localURI.QueryInterface(Ci.nsIFileURL).file.clone();
  1362.  
  1363.     LOG("saving definition to " + file.path);
  1364.  
  1365.     // Write the generator XML to the local file.
  1366.     var outputStream = Cc["@mozilla.org/network/safe-file-output-stream;1"].
  1367.                        createInstance(Ci.nsIFileOutputStream);
  1368.     var localFile = file.QueryInterface(Ci.nsILocalFile);
  1369.     outputStream.init(localFile, (MODE_WRONLY | MODE_TRUNCATE | MODE_CREATE),
  1370.                       PERMS_FILE, 0);
  1371.     var serializer = Cc["@mozilla.org/xmlextras/xmlserializer;1"].
  1372.                      createInstance(Ci.nsIDOMSerializer);
  1373.     serializer.serializeToStream(xmlDefinition, outputStream, null);
  1374.     if (outputStream instanceof Ci.nsISafeOutputStream) {
  1375.       try       { outputStream.finish() }
  1376.       catch (e) { outputStream.close()  }
  1377.     }
  1378.     else
  1379.       outputStream.close();
  1380.   },
  1381.  
  1382.   update: function MSD_update() {
  1383.     // Update this generator if it was downloaded from a remote source and has
  1384.     // been modified since we last downloaded it.
  1385.     var genURI = this.uri;
  1386.     if (genURI && /^urn:source:/i.test(genURI.spec)) {
  1387.       let genURL = genURI.spec.replace(/^urn:source:/, "");
  1388.       genURI = this._ios.newURI(genURL, null, null);
  1389.     }
  1390.  
  1391.     // Only continue if we have a valid remote URI
  1392.     if (!genURI || !/^https?/.test(genURI.scheme)) {
  1393.       LOG("generator did not have valid URI; skipping update: " + genURI.spec);
  1394.       return;
  1395.     }
  1396.  
  1397.     // We use a HEAD request to check if the generator has been modified since
  1398.     // the last time we downloaded it. If it has, we move to _preformUpdate() to
  1399.     // actually download and save the new generator.
  1400.     var t = this;
  1401.     var loadCallback = function(resource) {
  1402.       if (resource.status != 304)
  1403.         t._performUpdate(genURI);
  1404.       else
  1405.         LOG("generator is already up to date: " + genURI.spec);
  1406.       resource.destroy();
  1407.     };
  1408.     var errorCallback = function(resource) {
  1409.       resource.destroy();
  1410.     };
  1411.  
  1412.     var file = this.localURI.QueryInterface(Ci.nsIFileURL).file.clone();
  1413.     var lastmod = new Date(file.lastModifiedTime);
  1414.     LOG("updating generator: " + genURI.spec);
  1415.     var resource = new MicrosummaryResource(genURI);
  1416.     resource.lastMod = lastmod.toUTCString();
  1417.     resource.method = "HEAD";
  1418.     resource.load(loadCallback, errorCallback);
  1419.   },
  1420.  
  1421.   _performUpdate: function MSD__performUpdate(uri) {
  1422.     var t = this;
  1423.     var loadCallback = function(resource) {
  1424.       try     { t._handleUpdateLoad(resource) }
  1425.       finally { resource.destroy() }
  1426.     };
  1427.     var errorCallback = function(resource) {
  1428.       resource.destroy();
  1429.     };
  1430.  
  1431.     var resource = new MicrosummaryResource(uri);
  1432.     resource.load(loadCallback, errorCallback);
  1433.   },
  1434.  
  1435.   _handleUpdateLoad: function MSD__handleUpdateLoad(resource) {
  1436.     if (!resource.isXML)
  1437.       throw("update failed, downloaded resource is not XML: " + this.uri.spec);
  1438.  
  1439.     // Preserve the generator's ID.
  1440.     // XXX Check for redirects and update the URI if it changes.
  1441.     var generatorID = this.uri.spec;
  1442.     resource.content.documentElement.setAttribute("uri", generatorID);
  1443.  
  1444.     // Reinitialize this generator with the newly downloaded XML and save to disk.
  1445.     this.initFromXML(resource.content);
  1446.     this.saveXMLToFile(resource.content);
  1447.  
  1448.     // Let observers know we've updated this generator
  1449.     var obs = Cc["@mozilla.org/observer-service;1"].
  1450.               getService(Ci.nsIObserverService);
  1451.     obs.notifyObservers(this, "microsummary-generator-updated", null);
  1452.   }
  1453. };
  1454.  
  1455.  
  1456.  
  1457.  
  1458.  
  1459. // Microsummary sets are collections of microsummaries.  They allow callers
  1460. // to register themselves as observers of the set, and when any microsummary
  1461. // in the set changes, the observers get notified.  Thus a caller can observe
  1462. // the set instead of each individual microsummary.
  1463.  
  1464. function MicrosummarySet() {
  1465.   this._observers = [];
  1466.   this._elements = [];
  1467. }
  1468.  
  1469. MicrosummarySet.prototype = {
  1470.   // IO Service
  1471.   __ios: null,
  1472.   get _ios() {
  1473.     if (!this.__ios)
  1474.       this.__ios = Cc["@mozilla.org/network/io-service;1"].
  1475.                    getService(Ci.nsIIOService);
  1476.     return this.__ios;
  1477.   },
  1478.  
  1479.   QueryInterface: XPCOMUtils.generateQI([Ci.nsIMicrosummarySet,
  1480.                                          Ci.nsIMicrosummaryObserver]),
  1481.  
  1482.   // nsIMicrosummaryObserver
  1483.  
  1484.   onContentLoaded: function MSSet_onContentLoaded(microsummary) {
  1485.     for ( var i = 0; i < this._observers.length; i++ )
  1486.       this._observers[i].onContentLoaded(microsummary);
  1487.   },
  1488.  
  1489.   onError: function MSSet_onError(microsummary) {
  1490.     for ( var i = 0; i < this._observers.length; i++ )
  1491.       this._observers[i].onError(microsummary);
  1492.   },
  1493.  
  1494.   // nsIMicrosummarySet
  1495.  
  1496.   addObserver: function MSSet_addObserver(observer) {
  1497.     if (this._observers.length == 0) {
  1498.       for ( var i = 0 ; i < this._elements.length ; i++ )
  1499.         this._elements[i].addObserver(this);
  1500.     }
  1501.  
  1502.     // Register the observer, but only if it isn't already registered,
  1503.     // so that we don't call the same observer twice for any given change.
  1504.     if (this._observers.indexOf(observer) == -1)
  1505.       this._observers.push(observer);
  1506.   },
  1507.   
  1508.   removeObserver: function MSSet_removeObserver(observer) {
  1509.     //NS_ASSERT(this._observers.indexOf(observer) != -1,
  1510.     //          "can't remove microsummary observer " + observer + ": not registered");
  1511.   
  1512.     //this._observers =
  1513.     //  this._observers.filter(function(i) { observer != i });
  1514.     if (this._observers.indexOf(observer) != -1)
  1515.       this._observers.splice(this._observers.indexOf(observer), 1);
  1516.     
  1517.     if (this._observers.length == 0) {
  1518.       for ( var i = 0 ; i < this._elements.length ; i++ )
  1519.         this._elements[i].removeObserver(this);
  1520.     }
  1521.   },
  1522.  
  1523.   extractFromPage: function MSSet_extractFromPage(resource) {
  1524.     if (!resource.isXML && resource.contentType != "text/html")
  1525.       throw("page is neither HTML nor XML");
  1526.  
  1527.     // XXX Handle XML documents, whose microsummaries are specified
  1528.     // via processing instructions.
  1529.  
  1530.     var links = resource.content.getElementsByTagName("link");
  1531.     for ( var i = 0; i < links.length; i++ ) {
  1532.       var link = links[i];
  1533.  
  1534.       if(!link.hasAttribute("rel"))
  1535.         continue;
  1536.  
  1537.       var relAttr = link.getAttribute("rel");
  1538.  
  1539.       // The attribute's value can be a space-separated list of link types,
  1540.       // check to see if "microsummary" is one of them.
  1541.       var linkTypes = relAttr.split(/\s+/);
  1542.       if (!linkTypes.some( function(v) { return v.toLowerCase() == "microsummary"; }))
  1543.         continue;
  1544.  
  1545.  
  1546.       // Look for a TITLE attribute to give the generator a nice name in the UI.
  1547.       var linkTitle = link.getAttribute("title");
  1548.  
  1549.  
  1550.       // Unlike the "href" attribute, the "href" property contains
  1551.       // an absolute URI spec, so we use it here to create the URI.
  1552.       var generatorURI = this._ios.newURI(link.href,
  1553.                                           resource.content.characterSet,
  1554.                                           null);
  1555.  
  1556.       if (!/^https?$/i.test(generatorURI.scheme)) {
  1557.         LOG("can't load generator " + generatorURI.spec + " from page " +
  1558.             resource.uri.spec);
  1559.         continue;
  1560.       }
  1561.  
  1562.       var generator = new MicrosummaryGenerator(generatorURI, null, linkTitle);
  1563.       var microsummary = new Microsummary(resource.uri, generator);
  1564.       if (!this.hasItemForMicrosummary(microsummary))
  1565.         this.AppendElement(microsummary);
  1566.     }
  1567.   },
  1568.  
  1569.   /**
  1570.    * Determines whether the given microsumary is already represented in the
  1571.    * set.
  1572.    */
  1573.   hasItemForMicrosummary: function MSSet_hasItemForMicrosummary(aMicrosummary) {
  1574.     for (var i = 0; i < this._elements.length; i++) {
  1575.       if (this._elements[i].equals(aMicrosummary))
  1576.         return true;
  1577.     }
  1578.     return false;
  1579.   },
  1580.  
  1581.   // XXX Turn this into a complete implementation of nsICollection?
  1582.   AppendElement: function MSSet_AppendElement(element) {
  1583.     // Query the element to a microsummary.
  1584.     // XXX Should we NS_ASSERT if this fails?
  1585.     element = element.QueryInterface(Ci.nsIMicrosummary);
  1586.  
  1587.     if (this._elements.indexOf(element) == -1) {
  1588.       this._elements.push(element);
  1589.       element.addObserver(this);
  1590.     }
  1591.  
  1592.     // Notify observers that an element has been appended.
  1593.     for ( var i = 0; i < this._observers.length; i++ )
  1594.       this._observers[i].onElementAppended(element);
  1595.   },
  1596.  
  1597.   Enumerate: function MSSet_Enumerate() {
  1598.     return new ArrayEnumerator(this._elements);
  1599.   }
  1600. };
  1601.  
  1602.  
  1603.  
  1604.  
  1605.  
  1606. /**
  1607.  * An enumeration of items in a JS array.
  1608.  * @constructor
  1609.  */
  1610. function ArrayEnumerator(aItems) {
  1611.   this._index = 0;
  1612.   this._contents = [];
  1613.   if (aItems) {
  1614.     for (var i = 0; i < aItems.length; ++i) {
  1615.       if (!aItems[i])
  1616.         aItems.splice(i, 1);      
  1617.     }
  1618.   }
  1619.   this._contents = aItems;
  1620. }
  1621.  
  1622. ArrayEnumerator.prototype = {
  1623.   QueryInterface: XPCOMUtils.generateQI([Ci.nsISimpleEnumerator]),
  1624.   
  1625.   hasMoreElements: function() {
  1626.     return this._index < this._contents.length;
  1627.   },
  1628.   
  1629.   getNext: function() {
  1630.     return this._contents[this._index++];      
  1631.   }
  1632. };
  1633.  
  1634.  
  1635.  
  1636.  
  1637.  
  1638. /**
  1639.  * Outputs aText to the JavaScript console as well as to stdout if the
  1640.  * microsummary logging pref (browser.microsummary.log) is set to true.
  1641.  * 
  1642.  * @param aText
  1643.  *        the text to log
  1644.  */
  1645. function LOG(aText) {
  1646.   if (getPref("browser.microsummary.log", false)) {
  1647.     dump("*** Microsummaries: " +  aText + "\n");
  1648.     var consoleService = Cc["@mozilla.org/consoleservice;1"].
  1649.                          getService(Ci.nsIConsoleService);
  1650.     consoleService.logStringMessage(aText);
  1651.   }
  1652. }
  1653.  
  1654.  
  1655.  
  1656.  
  1657.  
  1658. /**
  1659.  * A resource (page, microsummary, generator, etc.) identifiable by URI.
  1660.  * This object abstracts away much of the code for loading resources
  1661.  * and parsing their content if they are XML or HTML.
  1662.  * 
  1663.  * @constructor
  1664.  * 
  1665.  * @param   uri
  1666.  *          the location of the resource
  1667.  *
  1668.  */
  1669. function MicrosummaryResource(uri) {
  1670.   // Make sure we're not loading javascript: or data: URLs, which could
  1671.   // take advantage of the load to run code with chrome: privileges.
  1672.   // XXX Perhaps use nsIScriptSecurityManager.checkLoadURI instead.
  1673.   if (uri.scheme != "http" && uri.scheme != "https" && uri.scheme != "file")
  1674.     throw NS_ERROR_DOM_BAD_URI;
  1675.  
  1676.   this._uri = uri || null;
  1677.   this._content = null;
  1678.   this._contentType = null;
  1679.   this._isXML = false;
  1680.   this.__authFailed = false;
  1681.   this._status = null;
  1682.   this._method = "GET";
  1683.   this._lastMod = null;
  1684.  
  1685.   // A function to call when we finish loading/parsing the resource.
  1686.   this._loadCallback = null;
  1687.   // A function to call if we get an error while loading/parsing the resource.
  1688.   this._errorCallback = null;
  1689.   // A hidden iframe to parse HTML content.
  1690.   this._iframe = null;
  1691. }
  1692.  
  1693. MicrosummaryResource.prototype = {
  1694.   // IO Service
  1695.   __ios: null,
  1696.   get _ios() {
  1697.     if (!this.__ios)
  1698.       this.__ios = Cc["@mozilla.org/network/io-service;1"].
  1699.                    getService(Ci.nsIIOService);
  1700.     return this.__ios;
  1701.   },
  1702.  
  1703.   get uri() {
  1704.     return this._uri;
  1705.   },
  1706.  
  1707.   get content() {
  1708.     return this._content;
  1709.   },
  1710.  
  1711.   get contentType() {
  1712.     return this._contentType;
  1713.   },
  1714.  
  1715.   get isXML() {
  1716.     return this._isXML;
  1717.   },
  1718.  
  1719.   get status()        { return this._status },
  1720.   set status(aStatus) { this._status = aStatus },
  1721.  
  1722.   get method()        { return this._method },
  1723.   set method(aMethod) { this._method = aMethod },
  1724.  
  1725.   get lastMod()     { return this._lastMod },
  1726.   set lastMod(aMod) { this._lastMod = aMod },
  1727.  
  1728.   // Implement notification callback interfaces so we can suppress UI
  1729.   // and abort loads for bad SSL certs and HTTP authorization requests.
  1730.   
  1731.   // Interfaces this component implements.
  1732.   interfaces: [Ci.nsIAuthPromptProvider,
  1733.                Ci.nsIAuthPrompt,
  1734.                Ci.nsIPrompt,
  1735.                Ci.nsIProgressEventSink,
  1736.                Ci.nsIInterfaceRequestor,
  1737.                Ci.nsISupports],
  1738.  
  1739.   // nsISupports
  1740.  
  1741.   QueryInterface: function MSR_QueryInterface(iid) {
  1742.     if (!this.interfaces.some( function(v) { return iid.equals(v) } ))
  1743.       throw Cr.NS_ERROR_NO_INTERFACE;
  1744.  
  1745.     // nsIAuthPrompt and nsIPrompt need separate implementations because
  1746.     // their method signatures conflict.  The other interfaces we implement
  1747.     // within MicrosummaryResource itself.
  1748.     switch(iid) {
  1749.     case Ci.nsIAuthPrompt:
  1750.       return this.authPrompt;
  1751.     case Ci.nsIPrompt:
  1752.       return this.prompt;
  1753.     default:
  1754.       return this;
  1755.     }
  1756.   },
  1757.  
  1758.   // nsIInterfaceRequestor
  1759.   
  1760.   getInterface: function MSR_getInterface(iid) {
  1761.     return this.QueryInterface(iid);
  1762.   },
  1763.  
  1764.   // Suppress UI and abort loads for files secured by authentication.
  1765.  
  1766.   // Auth requests appear to succeed when we cancel them (since the server
  1767.   // redirects us to a "you're not authorized" page), so we have to set a flag
  1768.   // to let the load handler know to treat the load as a failure.
  1769.   get _authFailed()         { return this.__authFailed; },
  1770.   set _authFailed(newValue) { return this.__authFailed = newValue },
  1771.  
  1772.   // nsIAuthPromptProvider
  1773.   
  1774.   getAuthPrompt: function(aPromptReason, aIID) {
  1775.     this._authFailed = true;
  1776.     throw Cr.NS_ERROR_NOT_AVAILABLE;
  1777.   },
  1778.  
  1779.   // HTTP always requests nsIAuthPromptProvider first, so it never needs
  1780.   // nsIAuthPrompt, but not all channels use nsIAuthPromptProvider, so we
  1781.   // implement nsIAuthPrompt too.
  1782.  
  1783.   // nsIAuthPrompt
  1784.  
  1785.   get authPrompt() {
  1786.     var resource = this;
  1787.     return {
  1788.       QueryInterface: XPCOMUtils.generateQI([Ci.nsIPrompt]),
  1789.       prompt: function(dialogTitle, text, passwordRealm, savePassword, defaultText, result) {
  1790.         resource._authFailed = true;
  1791.         return false;
  1792.       },
  1793.       promptUsernameAndPassword: function(dialogTitle, text, passwordRealm, savePassword, user, pwd) {
  1794.         resource._authFailed = true;
  1795.         return false;
  1796.       },
  1797.       promptPassword: function(dialogTitle, text, passwordRealm, savePassword, pwd) {
  1798.         resource._authFailed = true;
  1799.         return false;
  1800.       }
  1801.     };
  1802.   },
  1803.  
  1804.   // nsIPrompt
  1805.  
  1806.   get prompt() {
  1807.     var resource = this;
  1808.     return {
  1809.       QueryInterface: XPCOMUtils.generateQI([Ci.nsIPrompt]),
  1810.       alert: function(dialogTitle, text) {
  1811.         throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1812.       },
  1813.       alertCheck: function(dialogTitle, text, checkMessage, checkValue) {
  1814.         throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1815.       },
  1816.       confirm: function(dialogTitle, text) {
  1817.         throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1818.       },
  1819.       confirmCheck: function(dialogTitle, text, checkMessage, checkValue) {
  1820.         throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1821.       },
  1822.       confirmEx: function(dialogTitle, text, buttonFlags, button0Title, button1Title, button2Title, checkMsg, checkValue) {
  1823.         throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1824.       },
  1825.       prompt: function(dialogTitle, text, value, checkMsg, checkValue) {
  1826.         throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1827.       },
  1828.       promptPassword: function(dialogTitle, text, password, checkMsg, checkValue) {
  1829.         resource._authFailed = true;
  1830.         return false;
  1831.       },
  1832.       promptUsernameAndPassword: function(dialogTitle, text, username, password, checkMsg, checkValue) {
  1833.         resource._authFailed = true;
  1834.         return false;
  1835.       },
  1836.       select: function(dialogTitle, text, count, selectList, outSelection) {
  1837.         throw Cr.NS_ERROR_NOT_IMPLEMENTED;
  1838.       }
  1839.     };
  1840.   },
  1841.  
  1842.   // XXX We implement nsIProgressEventSink because otherwise bug 253127
  1843.   // would cause too many extraneous errors to get reported to the console.
  1844.   // Fortunately this doesn't screw up XMLHttpRequest, because it ensures
  1845.   // that its implementation of nsIProgressEventSink will always get called
  1846.   // in addition to whatever notification callbacks we set on the channel.
  1847.  
  1848.   // nsIProgressEventSink
  1849.  
  1850.   onProgress: function(aRequest, aContext, aProgress, aProgressMax) {},
  1851.   onStatus: function(aRequest, aContext, aStatus, aStatusArg) {},
  1852.  
  1853.   /**
  1854.    * Initialize the resource from an existing DOM document object.
  1855.    * 
  1856.    * @param   document
  1857.    *          a DOM document object
  1858.    *
  1859.    */
  1860.   initFromDocument: function MSR_initFromDocument(document) {
  1861.     this._content = document;
  1862.     this._contentType = document.contentType;
  1863.  
  1864.     // Normally we set this property based on whether or not
  1865.     // XMLHttpRequest parsed the content into an XML document object,
  1866.     // but since we already have the content, we have to analyze
  1867.     // its content type ourselves to see if it is XML.
  1868.     this._isXML = (this.contentType == "text/xml" ||
  1869.                    this.contentType == "application/xml" ||
  1870.                    /^.+\/.+\+xml$/.test(this.contentType));
  1871.   },
  1872.  
  1873.   /**
  1874.    * Destroy references to avoid leak-causing cycles.  Instantiators must call
  1875.    * this method on all instances they instantiate once they're done with them.
  1876.    *
  1877.    */
  1878.   destroy: function MSR_destroy() {
  1879.     this._uri = null;
  1880.     this._content = null;
  1881.     this._loadCallback = null;
  1882.     this._errorCallback = null;
  1883.     this._loadTimer = null;
  1884.     this._authFailed = false;
  1885.     if (this._iframe) {
  1886.       if (this._iframe && this._iframe.parentNode)
  1887.         this._iframe.parentNode.removeChild(this._iframe);
  1888.       this._iframe = null;
  1889.     }
  1890.   },
  1891.  
  1892.   /**
  1893.    * Load the resource.
  1894.    * 
  1895.    * @param   loadCallback
  1896.    *          a function to invoke when the resource finishes loading
  1897.    * @param   errorCallback
  1898.    *          a function to invoke when an error occurs during the load
  1899.    *
  1900.    */
  1901.   load: function MSR_load(loadCallback, errorCallback) {
  1902.     LOG(this.uri.spec + " loading");
  1903.   
  1904.     this._loadCallback = loadCallback;
  1905.     this._errorCallback = errorCallback;
  1906.  
  1907.     var request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance();
  1908.   
  1909.     var loadHandler = {
  1910.       _self: this,
  1911.       handleEvent: function MSR_loadHandler_handleEvent(event) {
  1912.         if (this._self._loadTimer)
  1913.           this._self._loadTimer.cancel();
  1914.  
  1915.         this._self.status = event.target.status;
  1916.  
  1917.         if (this._self._authFailed || this._self.status >= 400) {
  1918.           // Technically the request succeeded, but we treat it as a failure,
  1919.           // since we won't be able to extract anything relevant from the result.
  1920.  
  1921.           // XXX For now HTTP is the only protocol we handle that might fail
  1922.           // auth. This message will need to change once we support FTP, which
  1923.           // returns 0 for all statuses.
  1924.           LOG(this._self.uri.spec + " load failed; HTTP status: " + this._self.status);
  1925.           try     { this._self._handleError(event) }
  1926.           finally { this._self = null }
  1927.         }
  1928.         else if (event.target.channel.contentType == "multipart/x-mixed-replace") {
  1929.           // Technically the request succeeded, but we treat it as a failure,
  1930.           // since we aren't able to handle multipart content.
  1931.           LOG(this._self.uri.spec + " load failed; contains multipart content");
  1932.           try     { this._self._handleError(event) }
  1933.           finally { this._self = null }
  1934.         }
  1935.         else {
  1936.           LOG(this._self.uri.spec + " load succeeded; invoking callback");
  1937.           try     { this._self._handleLoad(event) }
  1938.           finally { this._self = null }
  1939.         }
  1940.       }
  1941.     };
  1942.  
  1943.     var errorHandler = {
  1944.       _self: this,
  1945.       handleEvent: function MSR_errorHandler_handleEvent(event) {
  1946.         if (this._self._loadTimer)
  1947.           this._self._loadTimer.cancel();
  1948.  
  1949.         LOG(this._self.uri.spec + " load failed");
  1950.         try     { this._self._handleError(event) }
  1951.         finally { this._self = null }
  1952.       }
  1953.     };
  1954.  
  1955.     // cancel loads that take too long
  1956.     // timeout specified in seconds at browser.microsummary.requestTimeout,
  1957.     // or 300 seconds (five minutes)
  1958.     var timeout = getPref("browser.microsummary.requestTimeout", 300) * 1000;
  1959.     var timerObserver = {
  1960.       _self: this,
  1961.       observe: function MSR_timerObserver_observe() {
  1962.         LOG("timeout loading microsummary resource " + this._self.uri.spec + ", aborting request");
  1963.         request.abort();
  1964.         try     { this._self.destroy() }
  1965.         finally { this._self = null }
  1966.       }
  1967.     };
  1968.     this._loadTimer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  1969.     this._loadTimer.init(timerObserver, timeout, Ci.nsITimer.TYPE_ONE_SHOT);
  1970.  
  1971.     request = request.QueryInterface(Ci.nsIDOMEventTarget);
  1972.     request.addEventListener("load", loadHandler, false);
  1973.     request.addEventListener("error", errorHandler, false);
  1974.     
  1975.     request = request.QueryInterface(Ci.nsIXMLHttpRequest);
  1976.     request.open(this.method, this.uri.spec, true);
  1977.     request.setRequestHeader("X-Moz", "microsummary");
  1978.     if (this.lastMod)
  1979.       request.setRequestHeader("If-Modified-Since", this.lastMod);
  1980.  
  1981.     // Register ourselves as a listener for notification callbacks so we
  1982.     // can handle authorization requests and SSL issues like cert mismatches.
  1983.     // XMLHttpRequest will handle the notifications we don't handle.
  1984.     request.channel.notificationCallbacks = this;
  1985.  
  1986.     // If this is a bookmarked resource, and the bookmarks service recorded
  1987.     // its charset in the bookmarks datastore the last time the user visited it,
  1988.     // then specify the charset in the channel so XMLHttpRequest loads
  1989.     // the resource correctly.
  1990.     try {
  1991.       var resolver = Cc["@mozilla.org/embeddor.implemented/bookmark-charset-resolver;1"].
  1992.                      getService(Ci.nsICharsetResolver);
  1993.       if (resolver) {
  1994.         var charset = resolver.requestCharset(null, request.channel, {}, {});
  1995.         if (charset != "");
  1996.           request.channel.contentCharset = charset;
  1997.       }
  1998.     }
  1999.     catch(ex) {}
  2000.  
  2001.     request.send(null);
  2002.   },
  2003.  
  2004.   _handleLoad: function MSR__handleLoad(event) {
  2005.     var request = event.target;
  2006.  
  2007.     if (request.responseXML) {
  2008.       this._isXML = true;
  2009.       // XXX Figure out the parsererror format and log a specific error.
  2010.       if (request.responseXML.documentElement.nodeName == "parsererror") {
  2011.         this._handleError(event);
  2012.         return;
  2013.       }
  2014.       this._content = request.responseXML;
  2015.       this._contentType = request.channel.contentType;
  2016.       this._loadCallback(this);
  2017.     }
  2018.  
  2019.     else if (request.channel.contentType == "text/html") {
  2020.       this._parse(request.responseText);
  2021.     }
  2022.  
  2023.     else {
  2024.       // This catches text/plain as well as any other content types
  2025.       // not accounted for by the content type-specific code above.
  2026.       this._content = request.responseText;
  2027.       this._contentType = request.channel.contentType;
  2028.       this._loadCallback(this);
  2029.     }
  2030.   },
  2031.  
  2032.   _handleError: function MSR__handleError(event) {
  2033.     // Call the error callback, then destroy ourselves to prevent memory leaks.
  2034.     try     { if (this._errorCallback) this._errorCallback(this) } 
  2035.     finally { this.destroy() }
  2036.   },
  2037.  
  2038.   /**
  2039.    * Parse a string of HTML text.  Used by _load() when it retrieves HTML.
  2040.    * We do this via hidden XUL iframes, which according to bz is the best way
  2041.    * to do it currently, since bug 102699 is hard to fix.
  2042.    * 
  2043.    * @param   htmlText
  2044.    *          a string containing the HTML content
  2045.    *
  2046.    */
  2047.   _parse: function MSR__parse(htmlText) {
  2048.     // Find a window to stick our hidden iframe into.
  2049.     var windowMediator = Cc['@mozilla.org/appshell/window-mediator;1'].
  2050.                          getService(Ci.nsIWindowMediator);
  2051.     var window = windowMediator.getMostRecentWindow("navigator:browser");
  2052.     // XXX We can use other windows, too, so perhaps we should try to get
  2053.     // some other window if there's no browser window open.  Perhaps we should
  2054.     // even prefer other windows, since there's less chance of any browser
  2055.     // window machinery like throbbers treating our load like one initiated
  2056.     // by the user.
  2057.     if (!window) {
  2058.       this._handleError(event);
  2059.       return;
  2060.     }
  2061.     var document = window.document;
  2062.     var rootElement = document.documentElement;
  2063.   
  2064.     // Create an iframe, make it hidden, and secure it against untrusted content.
  2065.     this._iframe = document.createElement('iframe');
  2066.     this._iframe.setAttribute("collapsed", true);
  2067.     this._iframe.setAttribute("type", "content");
  2068.   
  2069.     // Insert the iframe into the window, creating the doc shell.
  2070.     rootElement.appendChild(this._iframe);
  2071.  
  2072.     // When we insert the iframe into the window, it immediately starts loading
  2073.     // about:blank, which we don't need and could even hurt us (for example
  2074.     // by triggering bugs like bug 344305), so cancel that load.
  2075.     var webNav = this._iframe.docShell.QueryInterface(Ci.nsIWebNavigation);
  2076.     webNav.stop(Ci.nsIWebNavigation.STOP_NETWORK);
  2077.  
  2078.     // Turn off JavaScript and auth dialogs for security and other things
  2079.     // to reduce network load.
  2080.     // XXX We should also turn off CSS.
  2081.     this._iframe.docShell.allowJavascript = false;
  2082.     this._iframe.docShell.allowAuth = false;
  2083.     this._iframe.docShell.allowPlugins = false;
  2084.     this._iframe.docShell.allowMetaRedirects = false;
  2085.     this._iframe.docShell.allowSubframes = false;
  2086.     this._iframe.docShell.allowImages = false;
  2087.   
  2088.     var parseHandler = {
  2089.       _self: this,
  2090.       handleEvent: function MSR_parseHandler_handleEvent(event) {
  2091.         event.target.removeEventListener("DOMContentLoaded", this, false);
  2092.         try     { this._self._handleParse(event) }
  2093.         finally { this._self = null }
  2094.       }
  2095.     };
  2096.  
  2097.     // Convert the HTML text into an input stream.
  2098.     var converter = Cc["@mozilla.org/intl/scriptableunicodeconverter"].
  2099.                     createInstance(Ci.nsIScriptableUnicodeConverter);
  2100.     converter.charset = "UTF-8";
  2101.     var stream = converter.convertToInputStream(htmlText);
  2102.  
  2103.     // Set up a channel to load the input stream.
  2104.     var channel = Cc["@mozilla.org/network/input-stream-channel;1"].
  2105.                   createInstance(Ci.nsIInputStreamChannel);
  2106.     channel.setURI(this._uri);
  2107.     channel.contentStream = stream;
  2108.  
  2109.     // Load in the background so we don't trigger web progress listeners.
  2110.     var request = channel.QueryInterface(Ci.nsIRequest);
  2111.     request.loadFlags |= Ci.nsIRequest.LOAD_BACKGROUND;
  2112.  
  2113.     // Specify the content type since we're not loading content from a server,
  2114.     // so it won't get specified for us, and if we don't specify it ourselves,
  2115.     // then Firefox will prompt the user to download content of "unknown type".
  2116.     var baseChannel = channel.QueryInterface(Ci.nsIChannel);
  2117.     baseChannel.contentType = "text/html";
  2118.  
  2119.     // Load as UTF-8, which it'll always be, because XMLHttpRequest converts
  2120.     // the text (i.e. XMLHTTPRequest.responseText) from its original charset
  2121.     // to UTF-16, then the string input stream component converts it to UTF-8.
  2122.     baseChannel.contentCharset = "UTF-8";
  2123.  
  2124.     // Register the parse handler as a load event listener and start the load.
  2125.     // Listen for "DOMContentLoaded" instead of "load" because background loads
  2126.     // don't fire "load" events.
  2127.     this._iframe.addEventListener("DOMContentLoaded", parseHandler, true);
  2128.     var uriLoader = Cc["@mozilla.org/uriloader;1"].getService(Ci.nsIURILoader);
  2129.     uriLoader.openURI(channel, true, this._iframe.docShell);
  2130.   },
  2131.  
  2132.   /**
  2133.    * Handle a load event for the iframe-based parser.
  2134.    * 
  2135.    * @param   event
  2136.    *          the event object representing the load event
  2137.    *
  2138.    */
  2139.   _handleParse: function MSR__handleParse(event) {
  2140.     // XXX Make sure the parse was successful?
  2141.  
  2142.     this._content = this._iframe.contentDocument;
  2143.     this._contentType = this._iframe.contentDocument.contentType;
  2144.     this._loadCallback(this);
  2145.   }
  2146.  
  2147. };
  2148.  
  2149. /**
  2150.  * Get a resource currently loaded into a browser window.  Checks windows
  2151.  * one at a time, starting with the frontmost (a.k.a. most recent) one.
  2152.  * 
  2153.  * @param   uri
  2154.  *          the URI of the resource
  2155.  *
  2156.  * @returns a Resource object, if the resource is currently loaded
  2157.  *          into a browser window; otherwise null
  2158.  *
  2159.  */
  2160. function getLoadedMicrosummaryResource(uri) {
  2161.   var mediator = Cc["@mozilla.org/appshell/window-mediator;1"].
  2162.                  getService(Ci.nsIWindowMediator);
  2163.  
  2164.   // Apparently the Z order enumerator is broken on Linux per bug 156333.
  2165.   //var windows = mediator.getZOrderDOMWindowEnumerator("navigator:browser", true);
  2166.   var windows = mediator.getEnumerator("navigator:browser");
  2167.  
  2168.   while (windows.hasMoreElements()) {
  2169.     var win = windows.getNext();
  2170.     var tabBrowser = win.document.getElementById("content");
  2171.     for ( var i = 0; i < tabBrowser.browsers.length; i++ ) {
  2172.       var browser = tabBrowser.browsers[i];
  2173.       if (uri.equals(browser.currentURI)) {
  2174.         var resource = new MicrosummaryResource(uri);
  2175.         resource.initFromDocument(browser.contentDocument);
  2176.         return resource;
  2177.       }
  2178.     }
  2179.   }
  2180.  
  2181.   return null;
  2182. }
  2183.  
  2184. /**
  2185.  * Get a value from a pref or a default value if the pref doesn't exist.
  2186.  *
  2187.  * @param   prefName
  2188.  * @param   defaultValue
  2189.  * @returns the pref's value or the default (if it is missing)
  2190.  */
  2191. function getPref(prefName, defaultValue) {
  2192.   try {
  2193.     var prefBranch = Cc["@mozilla.org/preferences-service;1"].
  2194.                      getService(Ci.nsIPrefBranch);
  2195.     switch (prefBranch.getPrefType(prefName)) {
  2196.     case prefBranch.PREF_BOOL:
  2197.       return prefBranch.getBoolPref(prefName);
  2198.     case prefBranch.PREF_INT:
  2199.       return prefBranch.getIntPref(prefName);
  2200.     }
  2201.   }
  2202.   catch (ex) { /* return the default value */ }
  2203.   
  2204.   return defaultValue;
  2205. }
  2206.  
  2207.  
  2208. // From http://lxr.mozilla.org/mozilla/source/browser/components/search/nsSearchService.js
  2209.  
  2210. /**
  2211.  * Removes all characters not in the "chars" string from aName.
  2212.  *
  2213.  * @returns a sanitized name to be used as a filename, or a random name
  2214.  *          if a sanitized name cannot be obtained (if aName contains
  2215.  *          no valid characters).
  2216.  */
  2217. function sanitizeName(aName) {
  2218.   const chars = "-abcdefghijklmnopqrstuvwxyz0123456789";
  2219.   const maxLength = 60;
  2220.  
  2221.   var name = aName.toLowerCase();
  2222.   name = name.replace(/ /g, "-");
  2223.   //name = name.split("").filter(function (el) {
  2224.   //                               return chars.indexOf(el) != -1;
  2225.   //                             }).join("");
  2226.   var filteredName = "";
  2227.   for ( var i = 0 ; i < name.length ; i++ )
  2228.     if (chars.indexOf(name[i]) != -1)
  2229.       filteredName += name[i];
  2230.   name = filteredName;
  2231.  
  2232.   if (!name) {
  2233.     // Our input had no valid characters - use a random name
  2234.     for (var i = 0; i < 8; ++i)
  2235.       name += chars.charAt(Math.round(Math.random() * (chars.length - 1)));
  2236.   }
  2237.  
  2238.   if (name.length > maxLength)
  2239.     name = name.substring(0, maxLength);
  2240.  
  2241.   return name;
  2242. }
  2243.  
  2244. function NSGetModule(compMgr, fileSpec) {
  2245.   return XPCOMUtils.generateModule([MicrosummaryService]);
  2246. }
  2247.